import type { Directive, DirectiveBinding } from 'vue'
import { useUserStore } from '@/stores/user'

/**
 * 权限指令
 * 使用方法：
 * 1. 直接使用权限码：v-permission="'p2z9f5t8'"
 * 2. 使用路由 actions（推荐）：v-permission="$route?.meta?.$actions?.['create'].code"
 * 3. 多个权限（满足任一即可）：v-permission="['p2z9f5t8', 'r4j6k8m2']"
 */
export const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()
    
    if (value) {
      let hasPermission = false
      
      if (typeof value === 'string') {
        // 字符串：直接作为权限码
        hasPermission = userStore.hasPermission(value)
      } else if (Array.isArray(value)) {
        // 数组：满足任一权限即可
        hasPermission = userStore.hasAnyPermission(value)
      } else if (typeof value === 'object' && value !== null) {
        // 对象：可能是 $route.meta.$actions.create 这样的引用，尝试获取其 code 属性
        const permCode = (value as any).code || String(value)
        hasPermission = userStore.hasPermission(permCode)
      }
      
      if (!hasPermission) {
        // 移除元素
        el.parentNode?.removeChild(el)
      }
    }
  },
  updated(el: HTMLElement, binding: DirectiveBinding) {
    // 更新时重新检查权限
    const { value } = binding
    const userStore = useUserStore()
    
    if (value) {
      let hasPermission = false
      
      if (typeof value === 'string') {
        hasPermission = userStore.hasPermission(value)
      } else if (Array.isArray(value)) {
        hasPermission = userStore.hasAnyPermission(value)
      } else if (typeof value === 'object' && value !== null) {
        const permCode = (value as any).code || String(value)
        hasPermission = userStore.hasPermission(permCode)
      }
      
      if (!hasPermission) {
        // 如果元素已存在但无权限，移除
        if (el.parentNode) {
          el.parentNode.removeChild(el)
        }
      }
    }
  },
}

export default permission

